/* PAKFILE.C
 * Packet file routines. All files in one larger file, not compressed
 *************
 * 29.08.2000 : Toni R„s„nen
 *              modifications/documentation for open source
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include "version.h"

typedef struct {  char name[13] __attribute__ ((packed));
                  int fpos __attribute__ ((packed));
                  int flength __attribute__ ((packed));
               }  pkgfilelisttype __attribute__ ((packed));


pkgfilelisttype pkgfile;

FILE *pkg_files[64];
char pkg_names[64][13];
int pkg_fpos[64];
int pkg_flen[64];
int pkg_currfile;
int pkg_filec;

// ************************************************
#ifndef PAK_DEVELIO

void open_package (char *name)
{  FILE *tied;
   int c;
   char temp[20];

   tied = fopen (name, "rb");

   if (tied == NULL)
     {  printf ("Fatal error: %s nonexistent.\n",name); exit(0);  }

   fread (temp, 12,1, tied); // "I P K G ^H^H^H^H K G B I"

   fread (&c, 4,1, tied);
   if (c < PAKFILE_VERSION)
     {  printf ("Fatal error: %s is for older version of game.\n",name); exit(0);  }
   
   fread (&c, 4,1, tied);

   while (c)
     {  pkg_files[pkg_filec] = tied;
        fread (&pkgfile, sizeof(pkgfilelisttype),1, tied);
        strcpy (pkg_names[pkg_filec], pkgfile.name);
        pkg_fpos[pkg_filec] = pkgfile.fpos;
        pkg_flen[pkg_filec] = pkgfile.flength;
        pkg_filec ++;
        c--;
     }

}

int ffseek (FILE *tied, int offset, int mode)
{  int o;
   if (pkg_currfile < 0) return 1;

   if (mode == SEEK_CUR)
     {  fseek (pkg_files[pkg_currfile], offset, SEEK_CUR);
        return 0;
     }
   if (mode == SEEK_SET)
     {  o = pkg_fpos[pkg_currfile] + offset;
        fseek (pkg_files[pkg_currfile], o, SEEK_SET);
        return (0);
     }
   if (mode == SEEK_END)
     {  o = pkg_fpos[pkg_currfile] + pkg_flen[pkg_currfile] + offset;
        fseek (pkg_files[pkg_currfile], o, SEEK_SET);
        return (0);
     }
   return (1);

}

int fftell (FILE *tied)
{  return ( ftell(tied) - pkg_fpos[pkg_currfile] );
}

FILE* ffopen (char *name, char *flags) // flags ignored
{  int i;
   for (i = 0; i < pkg_filec; i++)
     {  if ( stricmp(pkg_names[i],name) == 0) // FOUND FILE
          {  fseek (pkg_files[i], pkg_fpos[i], SEEK_SET);
             pkg_currfile = i;
             return pkg_files[i];
          }
     }
   return NULL; // "file not found"
}

int ffclose (FILE *tied)
{  pkg_currfile = -1;
   return 0;
}

// ************************************************

#endif

// ************************************************
